<template>
    <div id="instructionInfo-content">
        <el-row class="form-content">
            <el-form label-width="69px">
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="产品代码(名称):">
                            <el-select v-model="searchForm.fundCode" filterable clearable size="mini">
                                <el-option
                                    v-for="i in fundCodeSelectData"
                                    :key="i.fundCode"
                                    :label="i.fundCode + ' ' + i.fundNameSt"
                                    :value="i.fundCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="证券代码(名称):">
                            <el-select
                                v-model="searchForm.stockCode"
                                filterable
                                clearable
                                @clear="getstockCodeList('')"
                                remote
                                :remote-method="getstockCodeList"
                                :loading="selectLoading"
                                size="mini"
                            >
                                <el-option v-for="i in stockReport" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="委托方向:">
                            <el-select v-model="searchForm.orderDirection" clearable size="mini">
                                <el-option
                                    v-for="item in orderDirectionData"
                                    :key="item.dictKey"
                                    :value="item.dictKey"
                                    :label="item.dictKeyName"
                                ></el-option>

                                <!-- <el-option value="5" label="融资回购">融资回购 </el-option>
                                <el-option value="6" label="融券回购">融券回购 </el-option> -->
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="证券类别:">
                            <el-select v-model="searchForm.stockType" filterable clearable size="mini">
                                <el-option v-for="item in stockType" :key="item.dictKey" :value="item.dictKey" :label="item.dictKeyName"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="业务类型:">
                            <el-select v-model="searchForm.businessType" clearable size="mini">
                                <el-option value="2" label="银行间业务"></el-option>
                                <!-- <el-option
                                    v-for="item in bussinessTypeData"
                                    :key="item.dictKey"
                                    :value="item.dictKey"
                                    :label="item.dictKeyName"
                                ></el-option> -->
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="3">
                        <el-button type="primary" size="mini" @click="query">查询</el-button>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="指令序号:">
                            <el-input size="mini" placeholder="" v-model="searchForm.instNo"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="指令状态:">
                            <el-select v-model="searchForm.instStatus" size="mini">
                                <!-- <el-option key="" value=""></el-option> -->
                                <el-option v-for="(value, key) in instructionStatus" :key="key" :value="key" :label="value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="4">
                        <el-form-item label="下达人:">
                            <el-select v-model="searchForm.directUser" filterable clearable size="mini">
                                <el-option
                                    v-for="item in orderUsers"
                                    :key="item.dictKey"
                                    :value="item.dictCode"
                                    :label="item.dictKey + ' ' + item.dictKeyName"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="下达日期:">
                            <el-date-picker
                                v-model="directDate"
                                type="date"
                                placeholder="请选择"
                                value-format="yyyyMMdd"
                                format="yyyy/MM/dd"
                                style="width: 100%"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-button type="primary" size="mini" @click="handleButtonClick('layout')">布局设置</el-button>
                        <el-button size="mini" @click="handleButtonClick('hide')" v-show="SHOW_SECURITY">{{
                            hideVisible ? '展开' : '隐藏'
                        }}</el-button>
                    </el-col>
                </el-row>
                <el-row v-if="!hideVisible">
                    <el-col :span="5">
                        <el-form-item label="资产单元编号(名称):">
                            <el-select v-model="searchForm.assetCode" filterable clearable size="mini">
                                <el-option
                                    v-for="i in assetCodeSelectData"
                                    :key="i.assetCode"
                                    :label="i.assetCode + ' ' + i.assetName"
                                    :value="i.assetCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="组合编码(名称):">
                            <el-select v-model="searchForm.fundAcCode" filterable clearable size="mini">
                                <el-option
                                    v-for="i in fundAccountCodeSelectData"
                                    :key="i.fundAccountCode"
                                    :label="i.fundAccountCode + ' ' + i.fundAccountName"
                                    :value="i.fundAccountCode"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="15"></el-col>
                </el-row>
            </el-form>
        </el-row>
        <el-row class="table-content">
            <div style="height: calc(100% - 60px)">
                <el-table
                    :key="tableKey"
                    :data="dataSource"
                    border
                    v-loading="tableLoading"
                    element-loading-text="加载中"
                    size="mini"
                    height="100%"
                    ref="table"
                    @row-click="handleRow"
                    style="cursor: pointer"
                    highlight-current-row
                    highlight-hover-row
                    fit
                    :default-sort="{ prop: sortProp, order: sortOrder }"
                    @sort-change="changeTableSort"
                >
                    <template v-for="(item, index) in showFieldList">
                        <el-table-column
                            show-overflow-tooltip
                            :key="index + 'name'"
                            :label="item.content"
                            :prop="item.id"
                            :min-width="item.minWidth"
                            :fixed="item.fixed"
                            :sortable="item.id == 'operate' ? false : 'custom'"
                            :sort-orders="['ascending', 'descending']"
                        >
                            <template slot="header">
                                <span>{{ item.content }}</span>
                            </template>
                            <template slot-scope="scope">
                                <span v-if="item.id == 'operate'">
                                    <el-button type="text" @click.stop="handleUpdateInst(scope.row)" :disabled="handleDisabled(scope.row)"
                                        >修改</el-button
                                    >
                                    <el-button type="text" @click.stop="handleBtnDel(scope.row)" :disabled="handleDisabled(scope.row)"
                                        >撤单</el-button
                                    >
                                </span>
                                <span v-else-if="item.id == 'factUseMoney'">
                                    {{
                                        Number(
                                            moment(scope.row.repurDate, 'YYYYMMDD')
                                                .diff(moment(scope.row.repoDate, 'YYYYMMDD'), 'days')
                                                .toString()
                                        ).toLocaleString()
                                    }}
                                </span>
                                <span v-else-if="item.id == 'instStatus'">
                                    {{ instructionStatus[scope.row.instStatus] }}
                                </span>
                                <span v-else-if="item.id == 'orderPriceType'">
                                    {{ investPriceSelectData[scope.row.orderPriceType] }}
                                </span>

                                <span v-else-if="item.id == 'clearSpeed'">
                                    {{ Invest.clearSpeed[scope.row[item.id]] }}
                                </span>
                                <span v-else-if="item.id == 'repoDate' || item.id == 'repurDate'">
                                    {{ formatterDate(scope.row[item.id]) }}
                                </span>
                                <span v-else-if="item.id == 'directTime'">
                                    {{ formatterDate(scope.row['directDate']) + ' ' + formatterTime(scope.row[item.id]) }}
                                </span>

                                <span v-else-if="['orderAmount', 'shouldInterest', 'expirePayBalance', 'repoBalance'].includes(item.id)">
                                    {{ scope.row[item.id] != undefined ? numberFormat(scope.row[item.id], 2) : '--' }}
                                </span>

                                <span v-else-if="item.id == 'repoDay'">
                                    {{ scope.row[item.id] != undefined ? numberFormat(scope.row[item.id]) : '--' }}
                                </span>

                                <span v-else-if="item.id == 'orderBalance'">
                                    {{ scope.row[item.id] != undefined ? numberFormat(scope.row[item.id], 2) : '--' }}
                                </span>
                                <span v-else-if="item.id === 'calculateValue' || item.id === 'thresholdValue'">
                                    {{
                                        scope.row[item.id] != undefined
                                            ? numberFormat(scope.row[item.id], scope.row.unit) + unitShow(scope.row.unit)
                                            : '--'
                                    }}
                                </span>
                                <span v-else-if="item.id == 'orderRate'">
                                    {{ accMul(scope.row[item.id], 100).toFixed(5) }}
                                </span>
                                <span v-else>{{ scope.row[item.id] || '--' }}</span>
                            </template>
                        </el-table-column>
                    </template>
                </el-table>
            </div>
            <el-pagination
                background
                @current-change="handleCurrentChange"
                layout="total, prev, pager, next"
                :current-page="pages.currentPage"
                :page-size="pages.pageSize"
                :total="pages.total"
            >
            </el-pagination>
        </el-row>
        <el-row class="tab-content">
            <el-tabs v-model="activeKey" style="height: 100%">
                <el-tab-pane label="指令明细" name="detail" class="inst-detail">
                    <div style="height: 100%; padding: 4px 10px; width: 100%; overflow-x: auto">
                        <div class="detail-row">
                            <el-tooltip placement="top" :content="clickRecord.instNo">
                                <span>
                                    指令序号：<span style="color: blue">{{ clickRecord.instNo }}</span>
                                </span>
                            </el-tooltip>

                            <span
                                >指令状态：<span style="color: blue">{{ instructionStatus[clickRecord.instStatus] }}</span>
                            </span>
                            <el-tooltip placement="top" :content="clickRecord.directUserName">
                                <span>
                                    下达人：<span style="color: blue">{{ clickRecord.directUserName }} </span>
                                </span>
                            </el-tooltip>
                            <span>
                                下达时间：<span style="color: blue">
                                    {{ formatterDate(clickRecord.directDate) + ' ' + formatterTime(clickRecord.directTime) }}</span
                                >
                            </span>

                            <!-- <span>
                                指令数量(张)：<span style="color: blue">{{ Number(clickRecord.orderAmount).toLocaleString() }}</span>
                            </span>
                            <span>
                                指令金额(元)：<span style="color: blue">{{
                                    Number(clickRecord.orderBalance).toLocaleString('zh', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
                                }}</span>
                            </span> -->
                        </div>
                        <div class="detail-row">
                            <el-tooltip placement="top" :content="clickRecord.fundCode">
                                <span>
                                    产品代码：<span style="color: blue">{{ clickRecord.fundCode }}</span>
                                </span>
                            </el-tooltip>
                            <el-tooltip placement="top" :content="clickRecord.fundName">
                                <span>
                                    产品名称：<span style="color: blue">{{ clickRecord.fundName }}</span>
                                </span>
                            </el-tooltip>
                            <el-tooltip placement="top" :content="clickRecord.assetCode">
                                <span v-show="SHOW_SECURITY">
                                    资产单元编号：<span style="color: blue">{{ clickRecord.assetCode }}</span>
                                </span>
                            </el-tooltip>
                            <el-tooltip placement="top" :content="clickRecord.assetName">
                                <span v-show="SHOW_SECURITY">
                                    资产单元名称：<span style="color: blue">{{ clickRecord.assetName }}</span>
                                </span>
                            </el-tooltip>
                            <el-tooltip placement="top" :content="clickRecord.groupCode">
                                <span>
                                    组合编码：<span style="color: blue">{{ clickRecord.groupCode }} </span>
                                </span>
                            </el-tooltip>
                            <el-tooltip placement="top" :content="clickRecord.groupName">
                                <span>
                                    组合名称：<span style="color: blue"> {{ clickRecord.groupName }}</span>
                                </span>
                            </el-tooltip>
                            <el-tooltip placement="top" :content="clickRecord.stockCode">
                                <span>
                                    证券代码：<span style="color: blue">{{ clickRecord.stockCode }}</span>
                                </span>
                            </el-tooltip>
                            <el-tooltip placement="top" :content="clickRecord.stockName">
                                <span v-show="!SHOW_SECURITY">
                                    证券名称：<span style="color: blue">{{ clickRecord.stockName }}</span>
                                </span>
                            </el-tooltip>
                            <span v-show="!SHOW_SECURITY">
                                投资类型：<span style="color: blue">{{ clickRecord.investTypeName }}</span>
                            </span>
                        </div>

                        <div class="detail-row">
                            <el-tooltip placement="top" :content="clickRecord.stockName">
                                <span v-show="SHOW_SECURITY">
                                    证券名称：<span style="color: blue">{{ clickRecord.stockName }}</span>
                                </span>
                            </el-tooltip>
                            <span v-show="SHOW_SECURITY">
                                投资类型：<span style="color: blue">{{ clickRecord.investTypeName }}</span>
                            </span>
                            <span>
                                业务类型：<span style="color: blue">{{ clickRecord.businessTypeName }}</span>
                            </span>
                            <span
                                >委托方向：<span style="color: blue">{{ clickRecord.orderDirectionName }}</span>
                            </span>

                            <span>
                                币种：<span style="color: blue"> {{ clickRecord.curName }}</span>
                            </span>
                            <span>
                                交易市场：<span style="color: blue">{{ clickRecord.marketName }}</span>
                            </span>
                        </div>

                        <div class="detail-row">
                            <span
                                >回购金额(元)：<span style="color: blue">{{
                                    clickRecord.repoBalance != undefined ? numberFormat(clickRecord.repoBalance, 2) : '--'
                                }}</span>
                            </span>
                            <span
                                >回购天数(天)：<span style="color: blue"
                                    >{{ clickRecord.repoDay ? Number(clickRecord.repoDay).toLocaleString() : clickRecord.repoDay }}
                                </span>
                            </span>
                            <span>
                                实际占款天数(天)：<span style="color: blue">
                                    {{ clickRecord.factUseMoney ? Number(clickRecord.factUseMoney).toLocaleString() : clickRecord.factUseMoney }}
                                    <!-- {{ moment(clickRecord.repurDate, 'YYYYMMDD').diff(moment(clickRecord.repoDate, 'YYYYMMDD'), 'days').toString() }} -->
                                </span>
                            </span>
                            <span>
                                首次结算日期：<span style="color: blue">{{ formatterDate(clickRecord.repoDate) }}</span>
                            </span>
                            <span>
                                到期结算日期：<span style="color: blue">{{ formatterDate(clickRecord.repurDate) }}</span>
                            </span>
                            <span>
                                清算速度：<span style="color: blue">{{ this.Invest.clearSpeed[clickRecord.clearSpeed] }}</span>
                            </span>
                            <span
                                >回购利率(%)：<span style="color: blue">{{
                                    clickRecord.orderRate != undefined ? numberFormat(accMul(clickRecord.orderRate, 100), 2) : '--'
                                }}</span>
                            </span>
                        </div>

                        <div class="detail-row">
                            <span>
                                应计利息(元)：<span style="color: blue">{{
                                    clickRecord.shouldInterest != undefined ? numberFormat(clickRecord.shouldInterest, 2) : '--'
                                }}</span>
                            </span>
                            <span
                                >到期回购金额：<span style="color: blue">{{
                                    clickRecord.expirePayBalance != undefined ? numberFormat(clickRecord.expirePayBalance, 2) : '--'
                                }}</span>
                            </span>
                            <el-tooltip placement="top" :content="clickRecord.opponentCode">
                                <span>
                                    交易对手代码：<span style="color: blue"> {{ clickRecord.opponentCode || '--' }}</span>
                                </span>
                            </el-tooltip>
                            <el-tooltip placement="top" :content="clickRecord.opponentName">
                                <span>
                                    交易对手名称：<span style="color: blue"> {{ clickRecord.opponentName || '--' }}</span>
                                </span>
                            </el-tooltip>
                        </div>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="指令证券" name="stock">
                    <div style="height: 100%; padding: 4px 10px">
                        <risk-table :msg="instStockMsg" v-loading="tabsLoading" :key="instStockTableKey"></risk-table>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="指令质押券" name="pledge">
                    <div style="height: 100%; padding: 4px 10px">
                        <risk-table :msg="instPledgeMsg" v-loading="tabsLoading"></risk-table></div
                ></el-tab-pane>
                <el-tab-pane label="指令结果" name="result">
                    <div style="height: 100%; padding: 4px 10px">
                        <risk-table
                            :msg="instResultMsg"
                            v-loading="tabsLoading"
                            @handleBtn="handleBtnLook"
                            :key="instResultMsgNumKey + 'instResultMsgNumKey'"
                            v-if="activeKey === 'result'"
                        ></risk-table></div
                ></el-tab-pane>
            </el-tabs>
        </el-row>

        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="REPO_TRIAL_CALCULATE"
            @on-submit="onSubmit"
        />

        <DeleteInvest
            :deleteBidShow="showDeleteInvst"
            :rowData="deleteRowData"
            @deleteBidReturn="deleteInvestReturn"
            v-if="showDeleteInvst"
        ></DeleteInvest>
    </div>
</template>
<script lang="ts">
import Invest from '@/common/dict/invest';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { dateFormat, PrefixInteger, timeFormat, numberFormat, unitShow, UUID, sortBy, convertNum, accMul, getConfigItem } from '@/utils/tools';
import moment from 'moment';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskTable from '@/common/components/risk-table.vue';
import ColumnUtil from '../utils/column-util';
import { getInstSelectOrderUser, getStockReportSelect } from '@/pages/baseparam/api';
import StatusTag from '@/pages/risk-measure/components/status-tag.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import DeleteInvest from '../invest-manage/deleteInvest.vue';
import { getUser } from '@/utils/user-util';

export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}
@Component({
    name: 'BayBackInstructionInfo',
    components: {
        RiskTable,
        StatusTag,
        RiskTableLayout,
        DeleteInvest,
    },
})
export default class BayBackInstructionInfo extends Vue {
    @Prop()
    renderCount: number;
    numberFormat = numberFormat;
    unitShow = unitShow;
    convertNum = convertNum;
    accMul = accMul;
    ColumnUtil = new ColumnUtil();
    Invest: any = new Invest();
    moment = moment;
    SHOW_SECURITY = getConfigItem('SHOW_SECURITY');

    // 查询表单
    searchForm: any = {
        assetTypes: [],
        businessType: '',
        // directDate: Number(moment().format('YYYYMMDD')),
        directUser: '',
        fundCode: '',
        instNo: '',
        instStatus: '1',
        marketTypes: [],
        orderDirection: '',
        stockCode: '',
        stockType: '',
        stockTypes: [],
        assetCode: '',
        fundAcCode: '',
        sort: 'D_DIRECT_DATE' + ' ' + 'DESC' + ',' + 'D_DIRECT_TIME' + ' ' + 'DESC',
    };

    // 撤单表单
    cancelOrder: any = {
        cancelOrderType: '2',
        tradeUser: getUser().userCode, // 当前用户
        tradeUserName: getUser().userName, // 当前用户
        orderType: '4',
        instructionType: '10',
        instNo: '',
        originOuterOrderCode: '',
        outerOrderCode: UUID() + '-' + new Date().getTime(),
        requestId: UUID() + '-' + new Date().getTime(),
    };
    investPriceSelectData: any = {}; // 价格模式下拉数据
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据

    listMsgNumKey: number = 0; // 指令数据Key
    dataSource: any[] = []; // 指令表数据

    pages: pages = {
        pageSize: 50,
        currentPage: 1,
        total: 0,
    };
    directDate: string = '';

    instructionStatus = {
        '0': '已归档',
        '1': '已下达成功',
        '3': '已撤销',
    };

    // 全部表格列
    tableColumns: any[] = [
        { content: '指令序号', id: 'instNo', minWidth: 120, fixed: 'left' },
        { content: '产品代码', id: 'fundCode', minWidth: 120 },
        { content: '产品名称', id: 'fundName', minWidth: 120 },
        { content: '组合编码', id: 'groupCode', minWidth: 150 },
        { content: '组合名称', id: 'groupName', minWidth: 150 },
        { content: '证券代码', id: 'stockCode', minWidth: 120 },
        { content: '证券名称', id: 'stockName', minWidth: 120 },
        { content: '业务类型', id: 'businessTypeName', minWidth: 120 },
        { content: '委托方向', id: 'orderDirectionName', minWidth: 120 },
        { content: '投资类型', id: 'investTypeName', minWidth: 120 },
        // { content: '价格模式', id: 'orderPriceType', minWidth: 120 },
        // { content: '指令价格(元)', id: 'orderPrice', minWidth: 140 },
        // { content: '指令数量(张)', id: 'orderAmount', minWidth: 140 },
        // { content: '指令金额(元)', id: 'orderBalance', minWidth: 140 },
        { content: '币种', id: 'curCode', minWidth: 100 },
        { content: '交易市场', id: 'marketName', minWidth: 120 },

        { content: '回购利率(%)', id: 'orderRate', minWidth: 150 },
        { content: '回购金额(元)', id: 'repoBalance', minWidth: 150 },
        { content: '回购天数(天)', id: 'repoDay', minWidth: 150 },
        { content: '实际占款天数(天）', id: 'factUseMoney', minWidth: 180 },
        { content: '应计利息(元)', id: 'shouldInterest', minWidth: 150 },
        { content: '清算速度', id: 'clearSpeed', minWidth: 150 },
        { content: '到期回购金额', id: 'expirePayBalance', minWidth: 150 },
        { content: '交易对手代码', id: 'opponentCode', minWidth: 150 },

        { content: '交易对手名称', id: 'opponentName', minWidth: 150 },
        { content: '首次结算日期', id: 'repoDate', minWidth: 150 },
        { content: '到期结算日期', id: 'repurDate', minWidth: 150 },
        { content: '下达人', id: 'directUserName', minWidth: 100 },

        // { content: '下达人', id: 'directUser', minWidth: 100 },
        { content: '下达时间', id: 'directTime', minWidth: 120 },
        { content: '指令状态', id: 'instStatus', minWidth: 120, fixed: 'right' },
        { content: '操作', id: 'operate', minWidth: 120, fixed: 'right' },
    ];
    // 已选择字段列表(不包括固定字段)
    selectedFieldList: any[] = [];

    // 固定字段列表
    fixedFieldList: any[] = [
        { content: '指令序号', id: 'instNo', minWidth: 120, fixed: 'left' },
        { content: '指令状态', id: 'instStatus', minWidth: 120, fixed: 'right' },
        { content: '操作', id: 'operate', minWidth: 120, fixed: 'right' },
    ];

    showFieldList: any[] = []; // 要显示的表格列
    layoutDialog: boolean = false;

    activeKey: string = 'detail'; //  指令当前tabKey
    instStockTableKey: number = 0;

    // 指令结果表格相关
    instResultMsg = {
        returnData: {},
        dataKey: 'list',
        title: this.ColumnUtil.instResultColumns,
        localSearch: true, // 本地搜索
        checked: { on: false, option: false },
        hidePage: true,
        height: '100%',
    };

    // 指令证券表格相关
    instStockMsg = {
        returnData: { list: [] },
        dataKey: 'list',
        title: this.ColumnUtil.instStockColumns,
        checked: { on: false, option: false },
        hidePage: true,
        height: '100%',
    };

    instPledgeMsg = {
        returnData: {},
        dataKey: 'list',
        title: this.ColumnUtil.instPledgeColumns,
        checked: { on: false, option: false },
        hidePage: true,
        height: '100%',
    };

    tableLoading: boolean = false; // 结果表数据加载

    stockReport: any[] = []; // 证券代码下拉
    stockReportState: boolean = false;
    stockType: any[] = []; // 证券类别下拉
    orderUsers: any[] = []; // 下单人下拉列表

    tabsLoading: boolean = false;
    stockLoading: boolean = false;
    clickRecord: any = {}; // 当前主表格点击的条目
    rowClickSetTime = null;
    instructionDetail: any = {};
    instStockDataSource: any[] = []; // 指令证券表数据
    instPledgeDataSource: any[] = []; // 指令质押券表数据
    instResultDataSource: any[] = []; // 指令结果表数据
    type: string = '';

    deleteRowData: any = {}; // 撤单行
    showDeleteInvst: boolean = false; // 撤单弹框
    tableKey: number = 0;

    sortProp: string = 'directTime'; // 排序字段
    sortOrder: string = 'descending'; // 排序方式
    commonField = this.ColumnUtil.commonFieldSort;
    marketCodes: any = {};

    // 委托方向下拉数据
    orderDirectionData: any[] = [];
    // 业务类型下拉数据
    bussinessTypeData: any[] = [];

    @Watch('renderCount')
    onWatchRenderCount() {
        this.getInstruction(this.searchForm, this.pages);
    }

    hideVisible: boolean = true; // 是否隐藏
    assetCodeSelectData: any[] = [];
    fundAccountCodeSelectData: any[] = [];
    async mounted() {
        if (this.SHOW_SECURITY) {
            this.$axios.get('/asset/list/byFundCode').then((res: any) => {
                this.assetCodeSelectData = res;
            });
            this.$axios.get('/fdAc/list/byFundCode').then((res: any) => {
                this.fundAccountCodeSelectData = res;
            });
        }
        this.tableColumns = this.ColumnUtil.handleTableColumns(this.tableColumns, 'id');
        // 价格模式
        let priceTypeTemp = await SGU_CACHE('PriceType', '/dict/list/code/Y_000237', []);
        this.investPriceSelectData = DictionConstUtil.ListToPojo(priceTypeTemp); // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfoByUser', '/fundInfo/list/byUser/like', []);
        // 证券类别
        this.getStockType(); // 获取证券代码下拉框数据
        this.getstockCodeList('');

        // 获取委托方向下拉框数据
        this.getBusinessTypeData();
        // 获取业务类型下拉框数据
        this.getOrderDirectionData();
        // 下单人下拉列表
        this.$axios.post('instruction/user/select').then((res: any) => {
            this.orderUsers = res;
        });
        this.queryLayout();

        // 获取指令信息
        this.getInstruction(this.searchForm, this.pages);

        this.marketCodes = DictionConstUtil.ListToPojo(await DictionConstUtil.FNMarketType());

        let columns = this.ColumnUtil.instStockColumns;

        columns.splice(11, 1, {
            name: '回购利率(%)',
            val: 'instPrice',
            width: 100,
            type: 'func',
            funcBody: value => (value != undefined ? numberFormat(accMul(value, 100), 2) : '--'),
        });
        this.instStockMsg.title = columns;
        this.instStockTableKey++;
    }

    beforeUpdate() {
        this.$nextTick(() => {
            // 在数据加载完，重新渲染表格
            (this.$refs['table'] as any).doLayout();
        });
    }

    query() {
        this.searchForm.directDate = Number(this.directDate) || null;
        this.clickRecord = {};
        this.getInstruction(this.searchForm, { currentPage: 1, pageSize: 50 });
    }

    getInstruction(param: any, pages: any) {
        this.tableLoading = true;
        this.$axios
            .post('instruction/bankRepoInstruction', {
                ...this.searchForm,
                paging: {
                    currentPage: pages.currentPage,
                    pageSize: pages.pageSize,
                },
            })
            .then((res: any) => {
                this.dataSource = res.list;
                this.pages.total = res.total;
                if (this.dataSource.length) {
                    this.clickRecord = this.dataSource[0] || {};
                    // if (moment(this.clickRecord.directDate).isBefore(moment().format('YYYYMMDD'))) {
                    //     this.type = 'history';
                    // } else {
                    //     this.type = '';
                    // }
                    if (this.clickRecord.instStatus == '0') {
                        this.type = 'history';
                    } else {
                        this.type = '';
                    }
                    (this.$refs['table'] as any).setCurrentRow(this.dataSource[0]);
                    this.handleRow(this.clickRecord);
                } else {
                    this.$set(this.instStockMsg.returnData, 'list', []);
                    this.$set(this.instResultMsg.returnData, 'list', []);
                }
                this.tableLoading = false;
            })
            .catch(() => {
                this.tableLoading = false;
            });
    }

    // 获取业务类型
    getBusinessTypeData() {
        this.$axios.get('/dict/instruction/businessType/' + 3).then((res: any) => {
            this.bussinessTypeData = res;
        });
    }

    // 获取委托方向
    getOrderDirectionData() {
        this.$axios.get('/dict/instruction/direction/' + 3).then((res: any) => {
            this.orderDirectionData = res;
        });
    }

    getStockType() {
        this.$axios.get('/dict/instruction/stockType/' + 3).then((res: any) => {
            this.stockType = res;
        });
    }

    // 排序改变
    changeTableSort(column: any): void {
        this.sortProp = column.prop;
        this.sortOrder = column.order;
        let sortType = column.order == 'ascending' ? 'ASC' : column.order == 'descending' ? 'DESC' : '';
        this.searchForm.sort = this.findName(column.prop, sortType);
        this.getInstruction(this.searchForm, { currentPage: 1, pageSize: 50 });
    }

    // 获取排序字段名称
    findName(name: string, order: string): string {
        let value = '';
        let field = '';
        let allFields = { ...this.commonField, ...this.ColumnUtil.bankHGFieldSort };

        if (name === 'directTime') {
            value = 'D_DIRECT_DATE' + ' ' + order + ',' + 'D_DIRECT_TIME' + ' ' + order;
        } else {
            for (const key in allFields) {
                if (name === key) {
                    field = allFields[key];
                }
            }
            value = field + ' ' + order;
        }
        return value;
    }

    // 获取证券代码下拉框数据
    getstockCodeList(val: string) {
        this.stockReportState = true;
        this.$axios
            .post('/instruction/repoStockList', {
                dictKey: val,
                dictKeyName: val,
            })
            .then((res: any) => {
                this.stockReport = res;
                this.stockReportState = false;
            });
    }

    // 格式化日期
    formatterDate(cellValue) {
        return cellValue ? dateFormat(cellValue) : '';
    }

    //  格式化时间
    formatterTime(cellValue) {
        return cellValue ? timeFormat(cellValue) : '';
    }

    // 设置是否禁用
    handleDisabled(row: any): boolean {
        let userCode = getUser().userCode;
        return !(row['instStatus'] == '1' && (userCode == row.directUser || getUser().superuser));
    }

    // 修改指令
    async handleUpdateInst(row: any) {
        console.log(row, '修改行');
        await this.handleRow(row);
        console.log(this.instPledgeDataSource, 'this.instPledgeDataSource');

        this.$emit('changeTab', row, this.instPledgeDataSource);
    }

    // 查看按钮点击
    handleBtnLook(obj: any): void {
        this.$emit('handelOperate', { record: obj.row, history: this.type === 'history', clickRecord: this.clickRecord });
    }

    // 撤单事件
    handleBtnDel(row: any): void {
        // this.deleteRowData = row;
        // this.showDeleteInvst = true;
        this.cancelOrder.instNo = row.instNo;
        this.cancelOrder.originOuterOrderCode = row.outerOrderCode;
        this.$confirm('确认是否撤单?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
            .then(() => {
                this.$axios
                    .post('/dataEngine/order/cancelOrder', this.cancelOrder)
                    .then((res: any) => {
                        this.yh_message_success('撤单成功');
                        this.getInstruction(this.searchForm, { currentPage: 1, pageSize: 50 });
                    })
                    .catch(() => {
                        this.yh_message_error('撤单失败');
                    });
            })
            .catch(() => {
                this.yh_message_info('已取消撤单');
            });
    }

    // 撤单回调返回值
    deleteInvestReturn(status: boolean): void {
        this.showDeleteInvst = false;
        if (status) {
            this.getInstruction(this.searchForm, this.pages); // 获取指令信息
        }
    }

    // 按钮点击
    handleButtonClick(action: string): void {
        if (action === 'layout') {
            this.layoutDialog = true;
        } else if (action === 'hide') {
            this.hideVisible = !this.hideVisible;
            console.log(this.hideVisible, 'hideVisible');
        }
    }

    // 点击单行
    async handleRow(obj: any) {
        this.clickRecord = obj;
        this.clickRecord.factUseMoney = moment(this.clickRecord.repurDate, 'YYYYMMDD')
            .diff(moment(this.clickRecord.repoDate, 'YYYYMMDD'), 'days')
            .toString();
        const form = {
            serialNo: this.clickRecord.serialNo, // 流水号
            instNo: this.clickRecord.instNo, // 指令序号
            outOrderCode: this.clickRecord.outerOrderCode, // 外部指令序号
            showError: true, // 产品true, 浦银false
            dailyInstructionNo: this.clickRecord.dailyInstructionNo || 0, // 恒生指令序号
            indexDailyModify: this.clickRecord.indexDailyModify || 0, // 恒生指令修改次序
            sourceType: this.clickRecord.sourceType, // 数据来源类型 (判断是否外部指令下达)
        };
        if (obj.instStatus == '0') {
            this.type = 'history';
        } else {
            this.type = '';
        }
        let record = obj;
        this.tabsLoading = true;
        if (this.rowClickSetTime) {
            clearTimeout(this.rowClickSetTime);
            this.rowClickSetTime = null;
        }
        // this.rowClickSetTime = setTimeout(() => {
        let isHistory = this.type === 'history';
        let url = '';
        if (isHistory) {
            url = '/instruction/inst/history/all/new';
        } else {
            url = '/instruction/inst/all/new';
        }
        // if (isHistory) {
        //     url = '/instruction/inst/history/all/' + record.instNo + '/' + record.outerOrderCode;
        // } else {
        //     url = '/instruction/inst/all/' + record.instNo + '/' + record.outerOrderCode;
        // }
        await this.$axios.post(url, form).then((res: any) => {
            let instStockDataSource = [];
            if (res.deposits && res.deposits.length > 0) {
                instStockDataSource = instStockDataSource.concat(res.deposits);
            }
            if (res.repos && res.repos.length > 0) {
                instStockDataSource = instStockDataSource.concat(res.repos);
            }
            if (res.stocks && res.stocks.length > 0) {
                instStockDataSource = instStockDataSource.concat(res.stocks);
            }
            instStockDataSource.forEach((item, i) => (item.key = item.serialNo + '-' + i));
            if (res.pleds && res.pleds.length > 0) {
                res.pleds.forEach((item, i) => (item.key = item.serialNo + '-' + i));
            }
            if (res.results && res.results.length > 0) {
                res.results.forEach((item, i) => (item.key = item.entryCode + '-' + i));
                res.results = res.results.sort(sortBy('thresholdType', 'desc'));
            }
            this.tabsLoading = false;
            this.instructionDetail = record;
            this.instStockDataSource = instStockDataSource;
            this.$set(this.instStockMsg.returnData, 'list', this.instStockDataSource);
            this.instStockMsg.returnData.list.forEach(ele => {
                ele.marketCode = this.marketCodes[ele.marketCode];
            });
            this.instPledgeDataSource = res.pleds;
            // 处理质押券数据
            this.instPledgeDataSource.forEach(ele => {
                // 交易市场
                ele.marketName = this.marketCodes[ele.marketCode];
                // 券面总额
                ele.totalFacePrice = ele.totalFacePrice / 10000;
                // 成交金额
                ele.balance = (ele.totalFacePrice * ele.pledgeRate) / 100;
            });
            this.$emit('getPledge', this.instPledgeDataSource);
            this.$set(this.instPledgeMsg.returnData, 'list', this.instPledgeDataSource);
            this.instResultDataSource = res.results;
            this.$set(this.instResultMsg.returnData, 'list', this.instResultDataSource);
        });
        // }, 500);
    }

    // 分页
    handleCurrentChange(curPage: number): void {
        this.pages.currentPage = curPage;
        this.getInstruction(this.searchForm, this.pages);
    }

    async onSubmit(data) {
        await this.queryLayout();
    }

    // 获取页面布局信息
    async queryLayout() {
        // this.tableLoading = true;
        let resList: any = await new Promise((resolve, reject) => {
            this.$axios('/tableLayout/query/REPO_TRIAL_CALCULATE')
                .then((res: any) => {
                    resolve(res);
                })
                .catch(err => {
                    reject(err);
                });
        });
        if (resList) {
            this.selectedFieldList = JSON.parse(resList);
            // 新增固定列 考虑到该列已被存入数据库问题
            this.selectedFieldList = this.selectedFieldList.filter(item => {
                let distinctIds = this.fixedFieldList.filter(fixedFieldListItem => {
                    return fixedFieldListItem.id === item.id;
                });
                if (distinctIds.length > 0) {
                    return false;
                } else {
                    return true;
                }
            });
            this.selectedFieldList = this.selectedFieldList.filter(
                ele => !['orderPrice', 'orderAmount', 'orderBalance', 'orderPriceType', 'repoBalance;', 'directUser'].includes(ele.id)
            );
            this.selectedFieldList.forEach(ele => {
                // if (ele.content === '交易对手') {
                if (ele.id === 'opponentCode') {
                    ele.content = '交易对手代码';
                }
                if (ele.id === 'opponentName') {
                    ele.content = '交易对手名称';
                }
                // }
            });
            this.showFieldList = this.fixedFieldList.concat(this.selectedFieldList);
            this.tableKey++;
        } else {
            this.selectedFieldList = this.tableColumns;
            this.showFieldList = this.tableColumns;
            this.tableKey++;
        }
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/inst-info';
</style>
